package com.example.scrollview;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Scroller;

/**
 * Created by Administrator on 2016/9/28 0028.
 */

public class ScrollView extends View {
    private static final String TAG = "ScrollView";
    private Scroller mScroller;
    private int lastX,lastY;
    public ScrollView(Context context) {
        super(context);
        mScroller=new Scroller(context);
    }


    public ScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mScroller=new Scroller(context);
    }

    public ScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mScroller=new Scroller(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int x= (int) event.getX();
        int y= (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX= (int) event.getX();
                lastY= (int) event.getY();
            break;
            case MotionEvent.ACTION_MOVE:
                int offsetX=x-lastX;//移动距离x
                int offsetY=y-lastY;
                ((View)getParent()).scrollBy(-offsetX,-offsetY);
            break;
            case MotionEvent.ACTION_UP:
                //让其自动返回到初始位置，并设置整个动画时长。
                View viewGroup=((View)getParent());//得到父控件，操作scroll类方法才是移动内部子控件。
                mScroller.startScroll(viewGroup.getScrollX(),viewGroup.getScrollY(),-viewGroup.getScrollX(),-viewGroup.getScrollY(),3000);
                invalidate();
                break;
        }
        return true;
    }

    /**
     * 以下方法，不是绘制移动效果，只是为了滑动结束时候返回动画，对应ACTION_UP中startScroll
     */
    @Override
    public void computeScroll() {
        super.computeScroll();
        //mScroller.computeScrollOffset()一旦滑动结束，则返回FALSE。以下是模板代码
        if (mScroller.computeScrollOffset()) {
            ((View)getParent()).scrollTo(mScroller.getCurrX(),mScroller.getCurrY());
            invalidate();
        }
    }
}
